package com.greate.community.quartz;

import com.greate.community.entity.User;
import com.greate.community.service.UserService;
import com.greate.community.util.CommunityUtil;
import com.greate.community.util.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

@Slf4j
public class RealNameVerifyJob implements Job {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Override
    public void execute(JobExecutionContext context) {
        // 检查实名
        String redisKey = RedisKeyUtil.getRealNameKey();
        if (!redisTemplate.hasKey(redisKey)) {
            log.info("[RealName Verify Job Execution] no user need verify");
            return ;
        }
        BoundSetOperations operations = redisTemplate.boundSetOps(redisKey);
        if (operations == null || operations.size() == 0) {
            log.info("[RealName Verify Job Execution] no user need verify");
            return ;
        }

        log.info("[RealName Verify Job Execution] verify user start");
        while (operations.size() > 0) {
            this.checkRealName((Integer) operations.pop());
        }
        log.info("[RealName Verify Job Execution] verify user over");
    }

    public void checkRealName(int userId) {
        User user = userService.findAllUserById(userId);
        if (user == null || user.getAuditStatus() == 2) {
            return;
        }

        // 字段为空不通过
        if (StringUtils.isBlank(user.getStudentCardUrl()) ||
                StringUtils.isBlank(user.getStudentCode()) ||
                StringUtils.isBlank(user.getRealName()) ||
                StringUtils.isBlank(user.getInstitute()) ||
                StringUtils.isBlank(user.getProfessionalClass())) {
            log.info("[RealName Verify Job Execution] reject user: {}, message is blank", userId);
            userService.updateAuditStatus(userId, 3);
            return;
        }

        // 检查学号
        if (!CommunityUtil.checkStudentId(user.getStudentCode())) {
            log.info("[RealName Verify Job Execution] reject user: {}, student id is wrong", userId);
            userService.updateAuditStatus(userId, 3);
            return;
        }

        // 通过审核
        log.info("[RealName Verify Job Execution] accept user: {}", userId);
        userService.updateAuditStatus(userId, 2);
    }
}
